﻿#if !WINDOWS_PHONE
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System;
namespace DeepEarth.Map.Core.Composition
{
    public class DeepEarthCatalog
    {
        private static volatile DeepEarthCatalog instance;
        private static object syncRoot = new Object();

        private DeepEarthCatalog() { }

        public static DeepEarthCatalog Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new DeepEarthCatalog();
                        }
                    }
                }

                return instance;
            }
        }

        private AggregateCatalog Catalog = new AggregateCatalog();

        public void RegisterAssembly(Assembly assembly)
        {
            var existingCatalog = Catalog.Catalogs.OfType<AssemblyCatalog>().Where(ac => ac.Assembly.FullName == assembly.FullName).FirstOrDefault();

            if (existingCatalog == null)
            {
                this.Catalog.Catalogs.Add(new AssemblyCatalog(assembly));
            }
        }

        [ImportMany(AllowRecomposition = true)]
        public IEnumerable<IMap> IMaps { get; set; }

        public void Compose()
        {
            var container = new CompositionContainer(Catalog);
            container.ComposeParts(this);
        }

        public void Compose(object o)
        {
            var container = new CompositionContainer(Catalog);
            container.ComposeParts(o);
        }
    }
}
#endif
